<template>
  <div class="login index" :style='{"background-color": ground_color}'>
      <!-- 导航条 -->
    <div class="tabbar" :style="{background:tabbar_color}">
        <span>小小笔记本</span>
        <div class="others">
            <router-link class="selection" to="/"><i class="el-icon-s-promotion "></i>首页</router-link>
            <router-link class="selection" to="/about"><i class="el-icon-share"></i>关于</router-link>
            <div class="up_input">
                <el-input placeholder="搜索笔记内容" v-model="input" class="input-with-select">
                    <el-button slot="append" icon="el-icon-search"></el-button>
                </el-input>
            </div>
            <router-link v-if="not_Login" class="selection" to="/login">&nbsp; 登录</router-link> 
            <router-link v-if="not_Login" class="selection" to="/register">&nbsp; 注册</router-link> 
            <router-link v-if="!not_Login" class="selection" to="/personal_center">{{ this.name }}</router-link>
            </div>
    </div>

    <div class="drop login_box">
        <body id="poster" :style='{"background-color": background_color, "color": font_color}'>
            <el-form class="login-container" label-position="left" label-width="0px">
            <h1 style="color: tomato;" class="login_title">登录</h1>
            <el-form-item>
                <el-input @blur="check_name" type="text" v-model="username" auto-complete="off" placeholder="请输入用户名/手机"></el-input>
                <div v-if="error_username" style="color: red; margin-left: 10px; font-size: 14px; height: 10px;">{{ error_username_msg }}</div>
            </el-form-item>
            <el-form-item>
                <el-input @blur="check_pwd" type="password" v-model="password" auto-complete="off" placeholder="密码" ></el-input>
                <div v-if="error_pwd_null" style="color: red; margin-left: 10px; font-size: 14px; height: 10px;">{{ error_pwd_msg }}</div>
            </el-form-item>
            <el-form-item>
                <div style="display: flex;">
                    <el-input @blur="check_code" style="width: 140px" type="text" v-model="image_code" auto-complete="off" placeholder="验证码" @keyup.enter.native="login"></el-input>
                    <img @click="change_image_code" style="width: 120px; height: 40px; margin-left: 20px;" :src="image_code_url" alt="">
                </div>
                <div v-if="error_image_code" style="color: red; margin-left: 10px; font-size: 14px; height: 10px;">{{ error_image_code_msg }}</div>
            </el-form-item>
            <el-form-item style="width: 100%">
                <el-button type="primary" style="width: 100%;background: #505458;border: none" @click="login" @keyup.enter.native="login">登录</el-button>
                <router-link to="/register">没有账号？</router-link>
            </el-form-item>
            </el-form>
        </body>
    </div>
  </div>
</template>

<script>
import { color,host } from '../../network/color_check.js'
import Qs from 'qs'
import axios from 'axios';
import Cookies from 'js-cookie';

export default {
    name: 'login',
    data () {
        return {
            not_Login: true,
            name: '',

            input: '',
            ground_color: '#f4f4f4', // 背景色 #f4f4f4是原来的颜色，#22303f是暗黑色, 
            background_color: 'white', // 元素的背景颜色，white, #18222d!important
            font_color: 'black',
            a_color: 'pink',
            tabbar_color: 'pink',
            write_color: '#eff7ff', // #18222d!important

            error_pwd_null: false,
            error_username: false,
            error_image_code: false,
            error_username_msg: '请填写用户名/手机',
            error_image_code_msg: '请填写验证码',
            error_pwd_msg: '请输入密码',

            username: '',
            password: '',
            image_code: '',
            uuid: '',
            image_code_url: '',
        }
    },
    mounted() {
        var a = Cookies.get();
        // 遍历cookie的值
        for(let key in a){
            if( a[key] === '1' ) {
                this.not_Login = false;
                this.name = key;
                break;
            }
        }
        if( this.name === '' ){
            // this.not_Login = color.not_Login;
            this.not_Login = true;
        }

        this.ground_color = color.ground_color;
        this.background_color = color.background_color;
        this.font_color = color.font_color;
        this.tabbar_color = color.tabbar_color;
        this.a_color= color.a_color;
        this.write_color = color.write_color;
        this.value = color.value;
        this.get_uuid();
    },
    methods: {
        login() {
            // 需要写一个等待层
            // 校验参数
            if( this.error_username || this.error_pwd_null || this.error_image_code ) {
                this.$notify({
                        title: '提示',
                        message: '缺少必传参数!',
                        duration: 3000
                    });
                return ;
            }
            // 发送请求
            axios({
                url:  host.url+'/Users/login.htm',
                method: 'post',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},
                data: {
                    username: this.username,
                    password: this.password,
                    uuid: this.uuid,
                    image_code: this.image_code,
                },
                transformRequest: [function (data) {
                    data = Qs.stringify(data);
                    return data;
                }],
            })
            .then(successResponse => {//successResponse.data.code
                // console.log(successResponse);
                if( successResponse.data.code === 200 ){
                    this.$message({
                        message: '登录成功！',
                        type: 'success'
                    });
                    // 写入cookie
                    Cookies.set(this.username, 1, {expires:14});
                    this.not_Login = color.not_Login = false;
                    this.$router.replace({path: '/'});
                    this.$router.go(0);
                }else if( successResponse.data.code === 4001) {
                    this.error_image_code = true;
                    this.error_image_code_msg = '验证码有误';
                    this.get_uuid();
                }else if( successResponse.data.code === 4002 ) {
                    this.error_image_code = true;
                    this.error_image_code_msg = '验证码已失效';
                    this.get_uuid();
                }else if( successResponse.data.code === 0 ) {
                    this.error_pwd_msg = '密码错误！';
                    this.error_pwd_null = true;
                }
                
          })
          .catch(failResponse => {
                console.log(failResponse);
                this.get_uuid();
                this.$message.error('登录失败！');
          })
        },
        // 获取图形验证码
        get_uuid() {
            this.uuid = this.generateUUId();
            // console.log(this.uuid);
            axios.get( host.url+'/verification/image_codes/' + this.uuid +'.htm')
            .then(response => {
                this.image_code_url =  host.url+'/verification/image_codes/' + this.uuid +'.htm';
            })
            .catch(error => {
                console.log(error);
            })
        },
        // 验证码点击事件
        change_image_code() {
            this.get_uuid();
        },
        // 生成随机数
        generateUUId() {
            var code = '';
            var codeLength = 4;
            var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
            for (var i = 0; i < codeLength; i++) {
                var index = Math.floor(Math.random() * 9);
                code += random[index];
            }
            return code;
        },
        // 检查账号
        check_name() {
            // 如果用户输入的是手机号
            var re = /^1[345789]\d{9}$/;
            if(re.test(this.username)) {
                // 检查手机号是否存在
                axios.get( host.url+'/Users/mobile/' + this.username +'/count.htm', {
                        responseType: 'json'
                    })
                    .then(response => {
                        if (response.data.count != 1) {
                            this.error_username_msg = '该手机号未注册';
                            return ;
                        } else {
                            this.error_username = false;
                            this.error_username_msg = '请输入用户名/手机';
                            return ;
                        }
                    })
                    .catch(error => {
                        console.log(error);
                        this.error_username_msg = '网络错误';
                        return ;
                    })
            }else {
                var len = this.username.length;
                if(len<5||len>20) {
                    this.error_username = true;
                    this.error_username_msg = '请输入正确的用户名/手机';
                    return ;
                } else {
                        this.error_username = false;
                        // 检查用户是否存在
                        axios.get( host.url+'/Users/usernames/' + this.username +'/count.htm', {
                            responseType: 'json'
                        })
                        .then(response => {
                            if (response.data.count != 1) {
                                this.error_username = true;
                                this.error_username_msg = '用户名不存在';
                                return ;
                            } else {
                                this.error_username = false;
                                this.error_username_msg = '请输入用户名/手机';
                                return ;
                            }
                        })
                        .catch(error => {
                            console.log(error.response.data);
                            this.error_username_msg = '网络错误';
                            return ;
                        })
                    }
                }
            
        },
        // 检查密码是否输入
        check_pwd() {
            if( this.password.length === 0 ) {
                this.error_pwd_null = true;
                this.error_pwd_msg = '请输入密码';
            } else {
                this.error_pwd_null = false;
            }
        },
        // 验证图形验证码是否输入
        check_code() {
            if( this.image_code.length === 0 ) {
                this.error_image_code_msg = '验证码未填写';
                this.error_image_code = true;
            } else {
                this.error_image_code = false;
            }
        }
    },
}
</script>

<style>
.el-input__inner {
    background-color:blanchedalmond;
}
.el-input__inner:focus {
    background-color:white;
}
.All-title{
  color:coral;
  font-size: 25px;
  margin-left: 20px;
  margin-top: 40px;
}
#poster {
  background-position: center;
  background-size: cover;
}
.login-container {
  background-clip: padding-box;
  padding: 35px 35px 15px 35px;
}

.login_title {
  margin: 0px auto 20px auto;
  text-align: center;
  /* color: #505458; */
}
.login_box {
    width: 300px;
    height: 450px;;
    margin: 10px auto;
}
.index {
    font-family:  -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";
    /* background-size: cover; */
    /* overflow-y: auto; */
    width:100%;
    height: 100%;
    /* background: yellow; */
    position: absolute;
}
.drop {
  padding-top: 50px;
}
</style>